package wiki.kaizen.cloud.plugin.spring.scan.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import wiki.kaizen.cloud.plugin.spring.scan.handler.LogServiceHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Configuration
@Slf4j
public class KaizenPluginSpringDefaultConfig {

    /**
     * 启用 RequestContextListener
     * */
    @Bean
    @ConditionalOnMissingBean(RequestContextListener.class)
    public RequestContextListener requestContextListener(){
        return  new RequestContextListener();
    }
    /**
     * 默认日志处理
     * */
    @Bean
    @ConditionalOnMissingBean(LogServiceHandler.class)
    public LogServiceHandler defaultLogHandler(){

    	final String unserializable = "{}";
        return info -> {
            Map<String, Object> args = info.getArgs();
            //过滤 request / response / 文件类型 /等不能被序列化的内容
            Map<String, Object> collect = new HashMap<>();

            if(!args.isEmpty()){
                Set<Map.Entry<String, Object>> entries = args.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    Object value;
                    try {
                        value = JSON.toJSON(entry.getValue());
                    } catch (Exception e) {
                        value = unserializable;
                    }
                    collect.put(entry.getKey(),value);
                }

            }


            log.info(
                   "{}: {}发出请求 => 请求执行方法{}:{}({}) => 执行时间{}ms",
                   info.getValue(),
                   info.getIp(),
                   info.getClazz().getName(),
                   info.getMethod().getName(),
                   collect.isEmpty()?"":new JSONObject(collect).toString(),
                   info.getExcuteTime()
           );
        };
    }
}
